from app import create_app, db
from app.database import save_db_data
from app.models.user import User
from app.models.field import Field
from app.models.device import Sensor, SensorData
from app.models.task import Task
from datetime import datetime, timedelta

def init_test_data():
    """初始化测试数据"""
    now = datetime.utcnow()
    
    # 创建测试农田
    field1 = Field(
        name='测试农田1',
        area=100.5,
        current_crop='玉米'
    ).save()
    
    field2 = Field(
        name='测试农田2',
        area=80.0,
        current_crop='小麦'
    ).save()
    
    # 创建测试设备
    devices = [
        {
            'name': '土壤传感器1',
            'device_type': 'soil_moisture',
            'field_id': field1.id,
            'is_online': True
        },
        {
            'name': '气象站1',
            'device_type': 'weather',
            'field_id': field1.id,
            'is_online': True
        },
        {
            'name': '土壤传感器2',
            'device_type': 'soil_moisture',
            'field_id': field2.id,
            'is_online': False
        }
    ]
    
    for device_data in devices:
        Sensor(
            name=device_data['name'],
            device_type=device_data['device_type'],
            field_id=device_data['field_id'],
            is_online=device_data['is_online']
        ).save()
    
    # 创建测试任务
    tasks = [
        {
            'title': '灌溉任务',
            'description': '农田1需要进行灌溉，土壤墒情低于阈值',
            'status': 'pending',
            'priority': 1,
            'field_id': field1.id,
            'task_type': 'irrigation',
            'created_by': 1,
            'due_date': now + timedelta(days=1)
        },
        {
            'title': '施肥任务',
            'description': '农田2需要进行追肥',
            'status': 'in_progress',
            'priority': 2,
            'field_id': field2.id,
            'task_type': 'fertilizer',
            'created_by': 1,
            'due_date': now + timedelta(days=2)
        },
        {
            'title': '设备维护',
            'description': '土壤传感器2需要检修',
            'status': 'pending',
            'priority': 3,
            'field_id': field2.id,
            'task_type': 'maintenance',
            'created_by': 1,
            'due_date': now + timedelta(days=1)
        },
        {
            'title': '农药喷洒',
            'description': '农田1发现病虫害，需要及时处理',
            'status': 'completed',
            'priority': 1,
            'field_id': field1.id,
            'task_type': 'pesticide',
            'created_by': 1,
            'due_date': now - timedelta(days=1),
            'completed_at': now
        }
    ]
    
    for task_data in tasks:
        Task(
            title=task_data['title'],
            description=task_data['description'],
            status=task_data['status'],
            priority=task_data['priority'],
            field_id=task_data['field_id'],
            task_type=task_data['task_type'],
            created_by=task_data['created_by'],
            due_date=task_data['due_date'],
            completed_at=task_data.get('completed_at')
        ).save()
    
    # 保存所有数据
    save_db_data()
    print('Test data initialized')

def init_admin():
    """初始化管理员账号"""
    if not User.find_by_username('admin'):
        admin = User.create_user(
            username='admin',
            email='admin@example.com',
            password='admin',
            role='admin',
            is_active=True
        )
        save_db_data()
        print('Created admin user')
    else:
        print('Admin user already exists')

if __name__ == '__main__':
    app = create_app()
    with app.app_context():
        init_admin()
        init_test_data()